<template>
  <Dialog
    title="分配角色"
    :confirm="handleSubmit"
    @open="handleOpen"
    @cancel="handleDialogClosed"
  >
    <p><b>当前用户:</b>{{ props.currRow.username }}</p>
    <p><b>当前角色:</b>{{ props.currRow.role_name }}</p>
    <p>
      <b>分配的新角色:</b>
      <el-select
        v-model="roleValue"
        placeholder="请选择"
      >
        <el-option
          v-for="item in roleList"
          :key="item.id"
          :label="item.roleName"
          :value="item.id"
        />
      </el-select>
    </p>
  </Dialog>
</template>

<script lang='ts' setup>
import { ref } from 'vue'
import type { IRoles } from '@/api/types/user'
import Dialog from '@/components/Dialog.vue'
import { reqRoleList, reqUpdateRolePower } from '@/api/user'
import { ElMessage } from 'element-plus'

const roleValue = ref<number | string>('')
const roleList = ref<IRoles[]>([])

const props = defineProps({
  currRow: {
    type: Object,
    default: () => {}
  }
})
interface EmitsType {
  (e: 'success'): void
}

const emit = defineEmits<EmitsType>()

const getRoleList = async () => {
  const res = await reqRoleList()
  roleList.value = res
}

const handleOpen = () => {
  getRoleList()
}

const handleDialogClosed = () => {
  roleValue.value = ''
}

const handleSubmit = async () => {
  try {
    await reqUpdateRolePower(props.currRow.id, { rid: roleValue.value })
    ElMessage.success('分配角色成功')
    emit('success')
  } catch (err) {
    console.log('reqUpdateRolePower', err)
  }
}
</script>
<style lang='scss' scoped>
p{
  padding: 10px;
}
</style>
